<template>
  <div class="user-service-user">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <div class="header-info">
        <el-avatar :size="40" src="/images/mihoyo.jpg" />
        <div class="user-info">
          <h4>客服聊天</h4>
          <p>您好！有什么可以帮助您的吗？</p>
        </div>
      </div>
    </div>

    <!-- 消息区域 -->
    <div class="messages-container" ref="messagesContainer">
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="['message', message.role === 'user' ? 'user-message' : 'admin-message']"
      >
        <el-avatar 
          :size="32" 
          :src="message.role === 'user' ? userStore.userInfo.icon : '/images/mihoyo.jpg'" 
        />
        <div class="message-content">
          <div class="message-text">{{ message.text }}</div>
          <div class="message-time">{{ formatTime(message.timestamp) }}</div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="3"
        placeholder="请输入您的问题..."
        resize="none"
        @keydown.enter.prevent="handleSend"
        :disabled="!isConnected"
      />
      <div class="input-actions">
        <el-button type="primary" @click="handleSend" :disabled="!isConnected">
          发送
        </el-button>
        <el-button type="success" v-if="!isConnected" @click="connectService">
          联系客服
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { useUserStore } from '@/stores/modules/user'
import { searchOnlineAdmin, getChatHistory } from '@/api/chat'
import { ElMessage } from 'element-plus'

export default {
  name: 'UserService',
  data() {
    return {
      inputMessage: '',
      messages: [
        { role: 'admin', text: '您好，请问有什么可以帮您？', timestamp: Date.now() }
      ],
      socket: null, // WebSocket实例
      adminId: null, // 客服ID
      userStore: useUserStore(),
      isConnected: false // 是否已连接
    }
  },
  methods: {
    async connectService() {
      await this.initWebSocket()
    },
    async initWebSocket() {
      // 初始化 WebSocket 连接
      const token = this.userStore.accessToken || ''
      this.socket = new WebSocket(`ws://localhost:8080/api/chat/user?token=${encodeURIComponent(token)}`)
      // 监听 WebSocket 事件
      this.socket.onopen = async () => {
        console.log('WebSocket 已连接')
        ElMessage.success('已连接到聊天服务器')
        this.isConnected = true
      this.adminId = await searchOnlineAdmin()
      
      if (this.adminId != "暂无在线管理员") {
        this.messages.push({ role: 'admin', text: `您已连接到客服 ${this.adminId}`, timestamp: Date.now() })
      } else {
        this.messages.push({ role: 'admin', text: `暂无在线客服`, timestamp: Date.now() })
        return
      }
        // 发送连接消息
        this.socket.send(JSON.stringify({
          adminId: this.adminId,
          message: '连接到客服'
        }))
        //查询用户的历史聊天记录
        const res = await getChatHistory()
        console.log('查询用户的历史聊天记录', res)
        if (res.length > 0) {
          this.messages = res.map(item => ({
            role: item.fromType,
            text: item.content,
            timestamp: item.timestamp
          }))
        }
      }

      this.socket.onmessage = (event) => {
        const data = JSON.parse(event.data)
        console.log('收到客服消息:', data)
        if(data.type == 'adminDisconnected') return
        if(data.content == "客服已关闭"){
          this.messages.push({ role: 'admin', text: data.content, timestamp: Date.now() })
          this.isConnected = false
          this.socket.close()
          return  
        } 
        this.messages.push({ 
          role: 'admin', 
          text: data.content, 
          timestamp: data.timestamp || Date.now() 
        })
        this.scrollToBottom()
      }

      this.socket.onerror = (error) => {
        console.error('WebSocket 错误:', error)
        ElMessage.error('连接发生错误')
      }

      this.socket.onclose = () => {
        console.log('WebSocket 已关闭')
        ElMessage.warning('连接已断开')
      }
    },
    scrollToBottom() {//滚动到最底部
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    },
    handleSend() {
      if (this.inputMessage.trim()) {
        const timestamp = Date.now()
        this.messages.push({ 
          role: 'user', 
          text: this.inputMessage.trim(),
          timestamp: timestamp
        })
        
        // 通过 WebSocket 发送消息
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
          this.socket.send(JSON.stringify({
            toId: this.adminId,
            content: this.inputMessage.trim(),
            timestamp: timestamp
           }))
        }

        this.inputMessage = ''
        this.scrollToBottom()
      }
    },
    
    formatTime(timestamp) {
      if (!timestamp) return ''
      
      const date = new Date(timestamp)
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      
      return `${hours}:${minutes}`
    }
    
  },
  mounted() {
    // this.initWebSocket() // 组件加载时初始化 WebSocket
    this.scrollToBottom()
  },
  beforeUnmount() {
    // 组件销毁时关闭 WebSocket
    if (this.socket) {
      this.socket.close()
    }
    this.isConnected = false
  }
}
</script>

<style lang="scss" scoped>
.user-service-user {
  display: flex;
  flex-direction: column;
  height: 85vh;
  min-height: 500px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.chat-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%);
  color: white;

  .header-info {
    display: flex;
    align-items: center;
    gap: 12px;

    .user-info {
      h4 {
        margin: 0 0 4px 0;
        color: white;
      }

      p {
        margin: 0;
        color: white;
        font-size: 14px;
        opacity: 0.9;
      }
    }
  }
}

.messages-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f8f9fa;

  .message {
    display: flex;
    margin-bottom: 16px;
    gap: 12px;

    &.admin-message {
      flex-direction: row;

      .message-content {
        background: #fff;
        border: 1px solid #e4e7ed;
      }
    }

    &.user-message {
      flex-direction: row-reverse;

      .message-content {
        background: #409eff;
        color: white;
      }
    }

    .message-content {
      max-width: 60%;
      padding: 12px 16px;
      border-radius: 12px;

      .message-text {
        margin-bottom: 4px;
        line-height: 1.5;
      }

      .message-time {
        font-size: 12px;
        opacity: 0.7;
      }
    }
  }
}

.input-area {
  padding: 16px 20px;
  border-top: 1px solid #e6e6e6;
  background: #fff;
  display: flex;
  gap: 12px;

  .el-textarea {
    flex: 1;
  }

  .input-actions {
    display: flex;
    align-items: flex-end;
  }
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .message {
    max-width: 85%;
  }

  .input-area {
    flex-direction: column;
    gap: 8px;

    .input-actions {
      width: 100%;
      justify-content: flex-end;
    }
  }
}
</style>